package nsqio

import (
	"encoding/json"
	"gitee.com/liukexing/mqbroker/core/driver/logger"
	"gitee.com/liukexing/mqbroker/core/typedef"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
	"time"
)

func gc(tick time.Duration) {
	for {
		time.Sleep(tick / 2 * time.Second)
		for _, v := range pubConfig {
			stat, err := GetNsqStats(v)
			if err {
				continue
			}
			for _, topic := range stat.Topics {
				if len(topic.Channels) == 0 {
					DeleteTopic(v, topic.TopicName)
				}
				for _, channel := range topic.Channels {
					if len(channel.Clients) == 0 {
						DeleteChannel(v, topic.TopicName, channel.ChannelName)
					}
				}
			}
		}
		time.Sleep(tick / 2 * time.Second)
	}
}

func GetNsqStats(config typedef.NsqConfig) (typedef.NsqStats, bool) {
	stat := typedef.NsqStats{}
	rsp, err := http.Get("http://" + config.HostName + ":" + strconv.Itoa(config.Http) + "/stats?format=json")
	if logger.CheckErr(typedef.ErrInfo{
		Info: Config.Info,
		Err:  err,
	}) {
		return stat, true
	}
	data, err := ioutil.ReadAll(rsp.Body)
	if logger.CheckErr(typedef.ErrInfo{
		Info: Config.Info,
		Err:  err,
	}) {
		return stat, true
	}

	if logger.CheckErr(typedef.ErrInfo{
		Info: Config.Info,
		Err:  json.Unmarshal(data, &stat),
	}) {
		return stat, true
	}
	return stat, false
}

func DeleteTopic(config typedef.NsqConfig, topic string) {
	http.Post("http://"+config.HostName+":"+strconv.Itoa(config.Http)+"/topic/delete?"+"topic="+topic,
		"application/x-www-form-urlencoded",
		strings.NewReader(""))

}

func DeleteChannel(config typedef.NsqConfig, topic, channel string) {
	http.Post("http://"+config.HostName+":"+strconv.Itoa(config.Http)+"/channel/delete?"+"topic="+topic+"&channel="+channel,
		"application/x-www-form-urlencoded",
		strings.NewReader(""))

}
